package jwdt.wizards;

import java.util.HashMap;
import java.util.Map;

import jwdt.common.Constant;
import jwdt.vo.InitProDataSourceVo;

import org.eclipse.jface.dialogs.IDialogPage;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;

public class InitProFrameWorkWizardPage_2 extends WizardPage {
	
	private ISelection selection;
	
	private InitProDataSourceVo curInitProDataSourceVo;
	
	private Map<String,InitProDataSourceVo> initProDataSourceVoMap = new HashMap<String,InitProDataSourceVo>();
	
	public Map<String, InitProDataSourceVo> getInitProDataSourceVoMap() {
		return initProDataSourceVoMap;
	}

	private Text dataSource_Text;
	private Combo dataBaseType_Combo;
	private Text driverClassText;
	private Text databaseUrlText;
	private Text usernameText;
	private Text passwordText;
	private TabFolder tabFolder;
	private TabItem tabItemJdbc;
	private TabItem tabItemJndi; 
	private Text jndiNameText;
	private Button defaultDataSource;
	private Button addBtn;
	private Button delBtn;
	private Table table;
	
	private String[] header = {"Name","Type","DataSource","Default"};
	
	//事件
	ModifyListener modifyListener = new ModifyListener() {
		public void modifyText(ModifyEvent e) {
			//Text
			if(e.getSource() instanceof Text){
				pageAsVo(e.getSource());	
			}			
		}
	};
	SelectionListener selectionListener = new SelectionAdapter() {
		@Override
		public void widgetSelected(SelectionEvent e) {
			//TabFolder
			if(e.getSource() instanceof TabFolder){
				pageAsVo(e.getSource());	
			}				
			//Combo
			if(e.getSource() instanceof Combo){
				pageAsVo(e.getSource());				
			}
			//Button
			if(e.getSource() instanceof Button){					
				Button btn = (Button) e.getSource();	
				//isDefault
				if(btn.getData("name").equals("isDefault")){
					pageAsVo(e.getSource());
				}
				//Save
				if(btn.getData("name").equals("Save")){
					//验证
					String errorMessage = validatePage();
					if(errorMessage == null){
						//验证通过							
						//添加到数据源列表
						initProDataSourceVoMap.put(curInitProDataSourceVo.getDataSourceName(), curInitProDataSourceVo.clone());
						//使用数据规则
						initProDataSourceVoMapRule(curInitProDataSourceVo.getDataSourceName());
						//reload table
						reloadTable();
						//validate canFinish
						valCanFinish();
					}else{						
						setErrorMessage(errorMessage);	
						setPageComplete(false);
					}								
				}
				//Del
				if(btn.getData("name").equals("Del")){
					TableItem[] tableItems = table.getSelection();
					for(TableItem tableItem : tableItems){
						initProDataSourceVoMap.remove(tableItem.getText());
					}
					//使用数据规则
					if(initProDataSourceVoMap.size() > 0){							
						initProDataSourceVoMapRule((String)initProDataSourceVoMap.keySet().toArray()[0]);
					}						
					//reload table
					reloadTable();	
					//validate canFinish
					valCanFinish();
				}
			}
			//Table
			if(e.getSource() instanceof Table){
				Table table = (Table) e.getSource();
				TableItem[] tableItems = table.getSelection();
				for(TableItem tableItem : tableItems){
					String key = tableItem.getText();						
					InitProDataSourceVo initProDataSourceVo = initProDataSourceVoMap.get(key);
					voAsPage(initProDataSourceVo);						
				}
			}
		}
	};
	
	/**
	 * Constructor for SampleNewWizardPage.
	 * 
	 * @param pageName
	 */
	public InitProFrameWorkWizardPage_2(ISelection selection) {
		super("wizardPage");
		setTitle("InitProFrameWork");
		setDescription("for Dynamic Web Project(2.4/2.5) - DataSource.");
		
		this.selection = selection;
		
		curInitProDataSourceVo = new InitProDataSourceVo();
		curInitProDataSourceVo.setDefault(false);
		curInitProDataSourceVo.setDataSourceType(Constant.DATASOURCE_TYPE_JDBC);
	}

	/**
	 * @see IDialogPage#createControl(Composite)
	 */
	public void createControl(Composite parent) {
		Composite container = new Composite(parent, SWT.NULL);
		
		GridLayout container_layout = new GridLayout();
		container_layout.numColumns = 1;
		container_layout.makeColumnsEqualWidth = true;
		container_layout.verticalSpacing=9;
		container.setLayout(container_layout);				
				
		/**
		 * DataSource Setting
		 */		
		Group DataSource = new Group(container,SWT.NONE);
		DataSource.setText("DataSource Setting");
		
		GridLayout DataSource_layout = new GridLayout();
		DataSource_layout.numColumns = 1;
		DataSource_layout.makeColumnsEqualWidth = true;
		DataSource.setLayout(DataSource_layout);		
		DataSource.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		
		//dataBaseType
		Composite dataBaseType = new Composite(DataSource, SWT.NONE);
		dataBaseType.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		
		GridLayout dataBaseType_layout = new GridLayout();
		dataBaseType_layout.numColumns = 2;
		dataBaseType_layout.makeColumnsEqualWidth = false;
		dataBaseType_layout.verticalSpacing=9;
		dataBaseType.setLayout(dataBaseType_layout);	
		
		//DataSource Name
		Label dataSource_Name = new Label(dataBaseType, SWT.NONE);		
		dataSource_Name.setText("DataSource Name：");
		dataSource_Name.setLayoutData(new GridData(GridData.BEGINNING));
		
		dataSource_Text = new Text(dataBaseType,SWT.BORDER | SWT.SINGLE);
		//注册事件
		dataSource_Text.addModifyListener(modifyListener);
		dataSource_Text.setData("name", "dataSourceName");
		dataSource_Text.setEditable(true);
		dataSource_Text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
				
		//DataBase Type
		Label dataBaseType_Name = new Label(dataBaseType, SWT.NONE);		
		dataBaseType_Name.setText("DataBase Type：");
		dataBaseType_Name.setLayoutData(new GridData(GridData.BEGINNING));
		
		dataBaseType_Combo = new Combo(dataBaseType, SWT.DROP_DOWN | SWT.READ_ONLY);
		dataBaseType_Combo.addSelectionListener(selectionListener);
		dataBaseType_Combo.setData("name", "dataBaseType");
		dataBaseType_Combo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		dataBaseType_Combo.setItems(Constant.DB_TYPE);
		
		//Jdbc/Jndi
		tabFolder = new TabFolder(DataSource, SWT.TOP);
		//注册事件
		tabFolder.addSelectionListener(selectionListener);
		tabFolder.setLayoutData(new GridData(GridData.FILL_BOTH));
				
		//Jdbc
		tabItemJdbc = new TabItem(tabFolder, SWT.NONE);
		tabItemJdbc.setData("name", Constant.DATASOURCE_TYPE_JDBC);
		tabItemJdbc.setText("Jdbc");
				
		Composite jdbcComposite = new Composite(tabFolder, SWT.NONE);
		jdbcComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
		
		GridLayout jdbcComposite_layout = new GridLayout();
		jdbcComposite_layout.numColumns = 2;
		jdbcComposite_layout.makeColumnsEqualWidth = false;
		jdbcComposite_layout.verticalSpacing=9;
		jdbcComposite.setLayout(jdbcComposite_layout);
		
		//Driver Class
		Label driverClassLabel = new Label(jdbcComposite, SWT.NONE);		
		driverClassLabel.setText("Driver Class：");
		driverClassLabel.setLayoutData(new GridData(GridData.BEGINNING));
		
		driverClassText = new Text(jdbcComposite,SWT.BORDER | SWT.SINGLE);
		//注册事件
		driverClassText.addModifyListener(modifyListener);
		driverClassText.setData("name", "driverClass");
		driverClassText.setEditable(true);
		driverClassText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		
		//Database Url Class
		Label databaseUrlLabel = new Label(jdbcComposite, SWT.NONE);		
		databaseUrlLabel.setText("Database Url：");
		databaseUrlLabel.setLayoutData(new GridData(GridData.BEGINNING));
		
		databaseUrlText = new Text(jdbcComposite,SWT.BORDER | SWT.SINGLE);
		//注册事件
		databaseUrlText.addModifyListener(modifyListener);
		databaseUrlText.setData("name", "dataBaseUrl");
		databaseUrlText.setEditable(true);
		databaseUrlText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		
		//Username Class
		Label usernameLabel = new Label(jdbcComposite, SWT.NONE);		
		usernameLabel.setText("Username：");
		usernameLabel.setLayoutData(new GridData(GridData.BEGINNING));
		
		usernameText = new Text(jdbcComposite,SWT.BORDER | SWT.SINGLE);
		//注册事件
		usernameText.addModifyListener(modifyListener);
		usernameText.setData("name", "userName");
		usernameText.setEditable(true);
		usernameText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		
		//Password Class
		Label passwordLabel = new Label(jdbcComposite, SWT.NONE);		
		passwordLabel.setText("Password：");
		passwordLabel.setLayoutData(new GridData(GridData.BEGINNING));
		
		passwordText = new Text(jdbcComposite,SWT.BORDER | SWT.SINGLE);
		//注册事件
		passwordText.addModifyListener(modifyListener);
		passwordText.setData("name", "passWord");
		passwordText.setEditable(true);
		passwordText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		
		tabItemJdbc.setControl(jdbcComposite);
		
		//Jndi
		tabItemJndi = new TabItem(tabFolder, SWT.NONE);
		tabItemJndi.setData("name", Constant.DATASOURCE_TYPE_JNDI);
		tabItemJndi.setText("Jndi");

		Composite jndiComposite = new Composite(tabFolder, SWT.NONE);
		jndiComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
		
		GridLayout jndiComposite_layout = new GridLayout();
		jndiComposite_layout.numColumns = 2;
		jndiComposite_layout.makeColumnsEqualWidth = false;
		jndiComposite_layout.verticalSpacing=9;
		jndiComposite.setLayout(jndiComposite_layout);

		//jndiName
		Label jndiNameLabel = new Label(jndiComposite, SWT.NONE);		
		jndiNameLabel.setText("Jndi Name：");
		jndiNameLabel.setLayoutData(new GridData(GridData.BEGINNING));
		
		jndiNameText = new Text(jndiComposite,SWT.BORDER | SWT.SINGLE);
		//注册事件
		jndiNameText.addModifyListener(modifyListener);
		jndiNameText.setData("name", "jndiName");
		jndiNameText.setEditable(false);
		jndiNameText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		
		tabItemJndi.setControl(jndiComposite);
		
		//是否为默认数据源
		defaultDataSource = new Button(DataSource,SWT.CHECK);
		//注册事件
		defaultDataSource.addSelectionListener(selectionListener);
		defaultDataSource.setData("name", "isDefault");
		defaultDataSource.setText("Default");
		defaultDataSource.setSelection(false);
		defaultDataSource.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		
		/**
		 * DataSource List
		 */		
		Group dataSourceList = new Group(container,SWT.NONE);		
		dataSourceList.setText("DataSource List");

		GridLayout dataSourceList_layout = new GridLayout();
		dataSourceList_layout.numColumns = 2;
		dataSourceList_layout.makeColumnsEqualWidth = false;
		dataSourceList.setLayout(dataSourceList_layout);		
		dataSourceList.setLayoutData(new GridData(GridData.FILL_BOTH));
			
		table = new Table(dataSourceList, SWT.BORDER | SWT.FULL_SELECTION);
		//注册事件
		table.addSelectionListener(selectionListener);
		//设置属性
		table.setData("name", "dataSourceList");
		table.setHeaderVisible(true);
		table.setLinesVisible(true);
		table.setLayoutData(new GridData(GridData.FILL_BOTH));

		for(String str : header){
			TableColumn tableColumn = new TableColumn(table, SWT.NONE);
			tableColumn.setText(str);
			tableColumn.setResizable(true);
		}
		
		for(int i=0 ; i<header.length ; i++){
			table.getColumn(i).pack();
		}
		
		Composite btns = new Composite(dataSourceList, SWT.NONE);
		btns.setLayoutData(new GridData(GridData.FILL_VERTICAL | GridData.VERTICAL_ALIGN_BEGINNING));
		
		GridLayout btns_layout = new GridLayout();
		btns_layout.numColumns = 1;
		btns_layout.makeColumnsEqualWidth = true;
		btns_layout.verticalSpacing=9;
		btns.setLayout(btns_layout);
					
		addBtn = new Button(btns, SWT.NONE);
		//注册事件
		addBtn.addSelectionListener(selectionListener);
		addBtn.setData("name", "Save");
		addBtn.setText("Save");
		addBtn.setLayoutData(new GridData(SWT.CENTER | GridData.FILL_HORIZONTAL));
		
		delBtn = new Button(btns, SWT.NONE);
		//注册事件
		delBtn.addSelectionListener(selectionListener);
		delBtn.setData("name", "Del");
		delBtn.setText("Del");
		delBtn.setLayoutData(new GridData(SWT.CENTER | GridData.FILL_HORIZONTAL));
		
		setControl(container);
	}
	
	//刷新Table
	private void reloadTable() {
		table.removeAll();		
		for (String key : initProDataSourceVoMap.keySet()) {
			InitProDataSourceVo initProDataSourceVo = initProDataSourceVoMap.get(key);
			
			TableItem tableItem = new TableItem(table,SWT.NONE);
			if(initProDataSourceVo.getDataSourceType().equals(Constant.DATASOURCE_TYPE_JDBC)){
				tableItem.setText(new String[]{
						initProDataSourceVo.getDataSourceName(),
						initProDataSourceVo.getDataSourceType(),
						initProDataSourceVo.getDataBaseUrl(),
						initProDataSourceVo.isDefault()? "Y":"N"});
			}
			if(initProDataSourceVo.getDataSourceType().equals(Constant.DATASOURCE_TYPE_JNDI)){
				tableItem.setText(new String[]{
						initProDataSourceVo.getDataSourceName(),
						initProDataSourceVo.getDataSourceType(),
						initProDataSourceVo.getJndiName(),
						initProDataSourceVo.isDefault()? "Y":"N"});
			}			
			
			for(int i=0 ; i<header.length ; i++){
				table.getColumn(i).pack();
			}
		}
	}
	
	//canFinish
	private void valCanFinish(){
		if(initProDataSourceVoMap.size() < 1){
			setPageComplete(false);
		}else{
			setPageComplete(true);		
		}
		setErrorMessage(null);	
	}
	
	//填充页面
	private void voAsPage(InitProDataSourceVo initProDataSourceVo) {
		dataSource_Text.setText(initProDataSourceVo.getDataSourceName());
		curInitProDataSourceVo.setDataSourceName(initProDataSourceVo.getDataSourceName());
		dataBaseType_Combo.setText(initProDataSourceVo.getDataBaseType());
		curInitProDataSourceVo.setDataBaseType(initProDataSourceVo.getDataBaseType());
		driverClassText.setText(initProDataSourceVo.getDriverClass());
		curInitProDataSourceVo.setDriverClass(initProDataSourceVo.getDriverClass());
		databaseUrlText.setText(initProDataSourceVo.getDataBaseUrl());
		curInitProDataSourceVo.setDataBaseUrl(initProDataSourceVo.getDataBaseUrl());
		usernameText.setText(initProDataSourceVo.getUserName());
		curInitProDataSourceVo.setUserName(initProDataSourceVo.getUserName());
		passwordText.setText(initProDataSourceVo.getPassWord());
		curInitProDataSourceVo.setPassWord(initProDataSourceVo.getPassWord());
		jndiNameText.setText(initProDataSourceVo.getJndiName());
		curInitProDataSourceVo.setJndiName(initProDataSourceVo.getJndiName());
		if(initProDataSourceVo.isDefault()){
			defaultDataSource.setSelection(true);
			curInitProDataSourceVo.setDefault(true);
		}else{
			defaultDataSource.setSelection(false);
			curInitProDataSourceVo.setDefault(false);
		}						
		if(initProDataSourceVo.getDataSourceType().equals(Constant.DATASOURCE_TYPE_JDBC)){			
			tabFolder.setSelection(tabItemJdbc);	
			curInitProDataSourceVo.setDataSourceType(Constant.DATASOURCE_TYPE_JDBC);
		}
		if(initProDataSourceVo.getDataSourceType().equals(Constant.DATASOURCE_TYPE_JNDI)){
			tabFolder.setSelection(tabItemJndi);	
			curInitProDataSourceVo.setDataSourceType(Constant.DATASOURCE_TYPE_JNDI);
		}
	}
	
	//获取Vo值
	private void pageAsVo(Object eventSource) {
		//Text
		if(eventSource instanceof Text){
			Text txt = (Text) eventSource;											
			if(txt.getData("name").equals("dataSourceName")){
				curInitProDataSourceVo.setDataSourceName(txt.getText().trim());
			}
			if(curInitProDataSourceVo.getDataSourceType().equals(Constant.DATASOURCE_TYPE_JDBC)){
				if(txt.getData("name").equals("driverClass")){
					curInitProDataSourceVo.setDriverClass(txt.getText().trim());
				}
				if(txt.getData("name").equals("dataBaseUrl")){
					curInitProDataSourceVo.setDataBaseUrl(txt.getText().trim());
				}
				if(txt.getData("name").equals("userName")){
					curInitProDataSourceVo.setUserName(txt.getText().trim());
				}
				if(txt.getData("name").equals("passWord")){
					curInitProDataSourceVo.setPassWord(txt.getText().trim());
				}
			}
			if(curInitProDataSourceVo.getDataSourceType().equals(Constant.DATASOURCE_TYPE_JNDI)){				
				if(txt.getData("name").equals("jndiName")){
					curInitProDataSourceVo.setJndiName(txt.getText().trim());
				}
			}
		}
		//TabFolder
		if(eventSource instanceof TabFolder){
			TabFolder tabFolder = (TabFolder) eventSource;
			int index = tabFolder.getSelectionIndex();
			TabItem tabItem = tabFolder.getItem(index);
			if(tabItem != null && tabItem.getData("name") != null){						
				curInitProDataSourceVo.setDataSourceType(tabItem.getData("name").toString());
			}					 					
		}
		//Combo
		if(eventSource instanceof Combo){
			Combo combo = (Combo) eventSource;
			if(combo.getData("name").equals("dataBaseType")){
				curInitProDataSourceVo.setDataBaseType(combo.getText());
			}					
		}
		//Button
		if(eventSource instanceof Button){
			Button btn = (Button)eventSource;
			if(btn.getData("name").equals("isDefault")){
				curInitProDataSourceVo.setDefault(!curInitProDataSourceVo.isDefault());
			}
		}
	}
	
	//验证
	private String validatePage(){
		String returnValue = null;
		
		if(curInitProDataSourceVo.getDataSourceName() == null || curInitProDataSourceVo.getDataSourceName().length() < 1){
			returnValue = "DataSource Name is empty.";			
			return returnValue;
		}
		if(curInitProDataSourceVo.getDataBaseType() == null || curInitProDataSourceVo.getDataBaseType().length() < 1){
			returnValue = "DataBase Type is empty.";			
			return returnValue;
		}
		if(curInitProDataSourceVo.getDataSourceType().equals(Constant.DATASOURCE_TYPE_JDBC)){
			if(curInitProDataSourceVo.getDataBaseUrl() == null || curInitProDataSourceVo.getDataBaseUrl().length() < 1){
				returnValue = "DataBase Url is empty.";				
				return returnValue;
			}
			if(curInitProDataSourceVo.getDriverClass() == null || curInitProDataSourceVo.getDriverClass().length() < 1){
				returnValue = "Driver Class is empty.";				
				return returnValue;
			}
			if(curInitProDataSourceVo.getUserName() == null || curInitProDataSourceVo.getUserName().length() < 1){
				returnValue = "Username is empty.";				
				return returnValue;
			}
			if(curInitProDataSourceVo.getPassWord() == null || curInitProDataSourceVo.getPassWord().length() < 1){
				returnValue = "Password is empty.";				
				return returnValue;
			}
		}else{
			if(curInitProDataSourceVo.getJndiName() == null || curInitProDataSourceVo.getJndiName().length() < 1){
				returnValue = "Jndi Name is empty.";				
				return returnValue;
			}
		}			
				
		return returnValue;
	}
	
	/*
	 * 如果是第一个，默认设置为默认数据源
	 * 如果为默认数据源，则设置其它为非默认
	 * 如果为无默认数据源，则设置为默认数据源
	 * jdbc&jndi Rule
	 */
	private void initProDataSourceVoMapRule(String key) {
		InitProDataSourceVo initProDataSource = initProDataSourceVoMap.get(key);
		/*
		 * 默认数据源Rule
		 */
		//如果是第一个，默认设置为默认数据源
		if(initProDataSourceVoMap.size() == 1){			
			initProDataSource.setDefault(true);
		}
		//如果是默认,设置其它为非默认
		if(initProDataSource.isDefault()){
			for(String keyStr : initProDataSourceVoMap.keySet()){
				if(!key.equals(keyStr)){
					InitProDataSourceVo initProDataSourceVar = initProDataSourceVoMap.get(keyStr);
					initProDataSourceVar.setDefault(false);
				}
			}
		}
		//如果数据源列表中没有默认数据源，设置为默认数据源
		if(initProDataSourceVoMap.size() > 1){	
			int defSum=0;
			for(String keyStr : initProDataSourceVoMap.keySet()){
				InitProDataSourceVo initProDataSourceVar = initProDataSourceVoMap.get(keyStr);
				if(initProDataSourceVar.isDefault()){
					defSum++;
				}		
			}
			if(defSum == 0){
				initProDataSource.setDefault(true);
			}
		}
	}
}